#include "command.h"

void command_user_gets(command_t *ct, int netFD, MYSQL *conn, client_t *cl){
    int n = 1;
    send(netFD, &n, sizeof(n), MSG_NOSIGNAL);

    char buf1[800] = { 0 };
    if(strcmp(cl->dir_path, "/") == 0){
        sprintf(buf1, "%s%s", cl->dir_path, ct->path);
    }else{
        sprintf(buf1, "%s/%s", cl->dir_path, ct->path);
    }
    char state[2048] = { 0 };
    sprintf(state, "select sha1 from file where file_name = '%s' and path = '%s'", ct->path, buf1);

    char sh[128] = { 0 };
    int n1 = mysql_select_get_one_str(conn, state, sh);
    if(n1 != 1){
        send(netFD, &n1, sizeof(int), MSG_NOSIGNAL);
    }else{
        send(netFD, &n1, sizeof(int), MSG_NOSIGNAL);
        char name[256] = { 0 };
        sprintf(name, "../user/%s", sh);
        int fd = open(name, O_RDONLY);
        struct stat fl;
        fstat(fd, &fl);

        send(netFD, &(fl.st_size), sizeof(off_t), MSG_NOSIGNAL);

        sendfile(netFD, fd, NULL, fl.st_size);

        close(fd);
    }
}
